package cn.com.hiocde.myresume.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v4.app.*;
import android.support.v4.view.*;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebView;
import android.widget.Toast;

import cn.com.hiocde.myresume.R;
import cn.com.hiocde.myresume.adapter.HomeFragmentPagerAdapter;
import cn.com.hiocde.myresume.fragment.ShowPlatformFragment;
import cn.com.hiocde.myresume.service.BgmService;

public class HomeActivity extends FragmentActivity  {

    private Intent bgmIntent;
    private boolean marked=false;//register menu checkbox status
    private ViewPager pager = null;
    private HomeFragmentPagerAdapter adapter=null;
    private PagerTabStrip tabStrip = null;
    private SensorManager sm;
    private long last_time=-1;//last time of vibrate mobile
    private int index=0;//page index
    private MenuItem bgm_closed=null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.activity_home);

        bgmIntent=new Intent(this, BgmService.class);
        startService(bgmIntent);//start bgm

        sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);//set sensor

        pager = (ViewPager) this.findViewById(R.id.viewpager);
        pager.setOffscreenPageLimit(2);//cache two pages in either side of current page
        tabStrip = (PagerTabStrip) this.findViewById(R.id.tabstrip);
        tabStrip.setDrawFullUnderline(false);
        tabStrip.setBackgroundColor(this.getResources().getColor(R.color.main));
        tabStrip.setTabIndicatorColor(this.getResources().getColor(R.color.color_accent));
        tabStrip.setTextSpacing(50);

        adapter=new HomeFragmentPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
        pager.setCurrentItem(0);    //no painting!!!
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){//only be called first
        getMenuInflater().inflate(R.menu.menu_main,menu);
        bgm_closed=menu.getItem(0);
        bgm_closed.setCheckable(true);

        //bgm_closed.setChecked(marked);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()) {
            case R.id.bgm_closed:
                if(marked){
                    marked=false;
                    item.setChecked(false);
                    startService(bgmIntent);
                    Toast.makeText(this, "Click it again close bgm", Toast.LENGTH_SHORT).show();
                }else{
                    marked=true;
                    item.setChecked(true);
                    stopService(bgmIntent);
                    Toast.makeText(this, "Click it again open bgm", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.exit:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        // TODO Auto-generated method stub
//        int index=pager.getCurrentItem();
//        if(index==2&&keyCode== KeyEvent.KEYCODE_BACK)
//        {
//            ShowPlatformFragment frag2=(ShowPlatformFragment)adapter.getItem(index);
//            WebView webView=frag2.getWebView();
//            if(webView.canGoBack()) {
//                webView.goBack();
//                return true;
//            }
//            else
//            {
//                System.exit(0);
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }

    @Override
    public void onBackPressed() {
        int index=pager.getCurrentItem();
        if(index==2){
            ShowPlatformFragment frag2 = (ShowPlatformFragment) adapter.getItem(index);
            WebView webView = frag2.getWebView();
            if(webView.canGoBack()){
                webView.goBack();
                return;
            }
        }

        new AlertDialog.Builder(this).setTitle("确认退出应用？")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        HomeActivity.this.finish();

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).show();
    }

    private SensorEventListener sensorEventListener = new SensorEventListener() {

        @Override
        public void onSensorChanged(SensorEvent event) {
            long cur_time=System.currentTimeMillis();
            if(last_time==-1){
                last_time=cur_time;
            }

            //Log.d("cur",cur_time+"");
            //Log.d("last",last_time+"");
            if((cur_time-last_time)<500){//shorter than 500us is good in fact
                //Log.d("into1","into1");
                return;
            }else{
                //Log.d("into2","into2");
                last_time=cur_time;

                float[] values = event.values;
                float x = values[0];
                float y = values[1];
                float z = values[2];
                float a=x*x+y*y+z*z;//in general , a=85
                //Log.d("a",a+"");

                if (a>110) {
                    //Log.d("into3","into3");
                    pager.setCurrentItem((++index)%3);//vibrate mobile , cut page
                }
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (sm != null) {//reset listener
            sm.registerListener(sensorEventListener, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    public void onStart(){
        super.onStart();
        if(!marked){
            startService(bgmIntent);
        }
    }

    @Override
    public void onStop(){
        super.onStop();
        if (sm != null) {           // cancel listener
            sm.unregisterListener(sensorEventListener);
        }

        stopService(bgmIntent);//close bgm when app stopped
    }

    public void onDestroy(){
        stopService(bgmIntent);//close bgm when exit app

        ShowPlatformFragment frag2 = (ShowPlatformFragment) adapter.getItem(2);
        unregisterReceiver(frag2.getConnectionReceiver());

        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());//end itself absolutely
    }
}
